package com.wesley.android.demo;

import com.wesley.android.demo.animation.Rotate3dAnimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.ImageView;

public class Rotate3dAnimationActivity extends Activity implements OnClickListener {
	
	private View mainLayout;
	
	private ImageView image1;
	private ImageView image2;
	
	private Animation startAnimation;
	private Animation endAnimation;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rotate_3d_animation_demo);

        mainLayout = (View) findViewById(R.id.mainLayout);
		image1 = (ImageView) findViewById(R.id.image_1);
		image2 = (ImageView) findViewById(R.id.image_2);
		
        ((Button) findViewById(R.id.button)).setOnClickListener(this);
    }
    
    public void setupStartAnimation() {
    	if(startAnimation == null) {
	    	startAnimation = new Rotate3dAnimation(0, 90, mainLayout.getWidth() / 2, mainLayout.getHeight() / 2, 1, false);
			startAnimation.setDuration(500L);
			startAnimation.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationEnd(Animation animation) {
					setupEndAnimation();
					if(animation.equals(image1.getAnimation())) {
						image1.setVisibility(View.INVISIBLE);
						image2.startAnimation(endAnimation);
					} else {
						image2.setVisibility(View.INVISIBLE);
						image1.startAnimation(endAnimation);
					}
				}
				@Override
				public void onAnimationRepeat(Animation animation) {}
				@Override
				public void onAnimationStart(Animation animation) {}
				
			});
    	}
    }
    
    public void setupEndAnimation() {
    	if(endAnimation == null) {
    		endAnimation = new Rotate3dAnimation(270, 360, mainLayout.getWidth() / 2, mainLayout.getHeight() / 2, 1, false);
    		endAnimation.setDuration(500L);
    		endAnimation.setAnimationListener(new AnimationListener() {
    			
    			@Override
    			public void onAnimationStart(Animation animation) {
    				if(image1.getAnimation().equals(animation)) {
    					image1.setVisibility(View.VISIBLE);
    				} else {
    					image2.setVisibility(View.VISIBLE);
    				}
    			}
    			
    			@Override
    			public void onAnimationRepeat(Animation animation) {}
    			
    			@Override
    			public void onAnimationEnd(Animation animation) {}
    		});
    	}
    }
    
	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.button) {
			setupStartAnimation();
			anim();
		}
	}
	
	public void anim() {
		if(image1.getVisibility() == View.VISIBLE) {
			image1.startAnimation(startAnimation);
		} else {
			image2.startAnimation(startAnimation);
		}
	}
}